<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">

      <!-- <span style="margin-left:10px">标题：</span>
      <el-input @keyup.enter.native="handleFilter" class="filter-item widht" placeholder="请输入关键字" v-model="listQuery.title" clearable>
      </el-input>
      
      <span style="margin-left:10px">作者：</span>
      <el-input v-model="listQuery.authorName" class="widht" placeholder="请输入资讯作者" clearable></el-input>
      
      <span style="margin-left:10px">热门推荐：</span>
      <el-select v-model="listQuery.recommend" placeholder="请选择" style="width: 120px;" clearable>
        <el-option label="是" :value='1'></el-option> 
        <el-option label="否" :value='0'></el-option>
      </el-select>      
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button> -->
      
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row :default-sort="{prop: 'inTime', order: 'descending'}" @selection-change="handleSelectionChange" @sort-change="getSortList" style="width: 100%">

      <el-table-column align="center" label="ID" min-width="50">
        <template slot-scope="scope">
          <span class="link-type">{{scope.row.id}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="110" align="center" label="升学路径" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.pathName}}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="110" align="center" label="图标" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.icon}}</span>
        </template>
      </el-table-column>

      <el-table-column width="400" align="center" label="筛选条件" >
        <template slot-scope="scope" style="textAlign: center" >
          <el-tag v-for="(item, index) of scope.row.conditionInfo" 
            :key="index" 
            closable 
            @close="deleteCondition(item, scope.row.id)"
            style="margin-right: 10px; margin-bottom: 10px;">
            {{ item.condition }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column width="400" align="center" label="关联课程" >
        <template slot-scope="scope" style="textAlign: center" >
          <el-tag 
            v-for="(item, index) of scope.row.courseInfo" 
            :key="index" 
            closable 
            @close="deleteCourse(item, scope.row.id)"
            style="margin-right: 10px; margin-bottom: 10px;"
          >{{ item.title }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column width="200" align="center" label="关联院校" type="expand">
        <template slot-scope="scope" style="textAlign: center" >
          <el-tag 
            v-for="(item, index) of scope.row.academyInfo" 
            :key="index" 
            closable 
            @close="deleteAcademy(item, scope.row.id)"
            style="margin-right: 10px; margin-bottom: 10px;"
          >{{ item.academyName }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column min-width="100" align="center" label="排序值" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.sort}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="small" @click="handleModifyStatus(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog top="4%" width="70%" title="编辑页" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form  label-width="100px">
        <el-form-item ref="temp" :rules="rules" :model="temp" label-position="right" label-width="100px" style='width: 70%; margin-left:50px;'>

          <el-form-item label="升学路径：" prop="pathName">
            <el-input type="textarea" maxlength="100" :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.pathName"></el-input>
          </el-form-item>
          <el-form-item label="上传图标：" prop="icon" style="margin-top:10px">
            <el-upload style="margin-left:10px" :headers="headers" v-model="temp.icon" action="/tools/oss/upload" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleUploadSuccess" list-type="picture" :file-list="temp.file" :limit="2" :accept="'.png,.jpg,.jpeg,.gif'">
              <el-button size="small" type="primary">上传图标</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="路径定义：" prop="pathDefine" style="margin-top:20px">
            <Tinymce :height=300 ref="editor" v-model="temp.pathDefine" :value="temp.pathDefine" />
          </el-form-item>

          <el-form-item label="适合人群：" prop="suitCrowd" style="margin-top:20px">
            <Tinymce :height=150 ref="editor" v-model="temp.suitCrowd" :value="temp.suitCrowd" />
          </el-form-item>

          <el-form-item label="考试时间：" prop="testSchedule" style="margin-top:20px">
            <Tinymce :height=150 ref="editor" v-model="temp.testSchedule" :value="temp.testSchedule" />
          </el-form-item>

          <el-form-item label="报考流程：" prop="process" style="margin-top:20px">
            <Tinymce :height=150 ref="editor" v-model="temp.process" :value="temp.process" />
          </el-form-item>

          <el-form-item label="考试形式：" prop="testForm" style="margin-top:20px">
            <Tinymce :height=150 ref="editor" v-model="temp.testForm" :value="temp.testForm" />
          </el-form-item>

          <el-form-item label="报考常识：" prop="commonSense" style="margin-top:20px">
            <Tinymce :height=150 ref="editor" v-model="temp.commonSense" :value="temp.commonSense" />
          </el-form-item>

          <el-form-item label="排序值：" prop="sort" style="margin-top:20px">
            <el-slider
              v-model="temp.sort" :value="temp.sort" show-input>
            </el-slider>
          </el-form-item>
          
          <el-form-item label="上传视频介绍：" prop="videoIntroduce" style="margin-top:20px">
              <el-input v-model="temp.videoIntroduce" type='text' style='display:none'></el-input>
              <el-upload
                ref="upload"
                :headers="headers"
                action="/tools/oss/uploadVideo"
                :before-upload="onBeforeUpload"
                :on-success="uploadSuccess"
                :on-remove="handleRemoveVideo"
                :on-progress="handProgress"
                :file-list="fileList"
                :show-file-list="false"
                :auto-upload="true"
                :accept="'.mp4'"
                :limit="2">
                <el-button slot="trigger" size="small" type="primary" plain>上传视频</el-button>
                <el-button size="small" type="danger"  @click="clearUpload">移除</el-button>
              </el-upload>
              <video
                v-if='temp.videoIntroduce' 
                ref="videoBox"
                id="testVideo" 
                class="video-js" 
                height="300px"
                preload="auto"
                controls="" 
                :src="temp.videoIntroduce">
              </video>
              <el-progress :text-inside="true" :stroke-width="16" :percentage="uploadProgress" v-show='uploadProgress'></el-progress>
          </el-form-item>

          <el-form-item label-width="100px" label="设置筛选条件：" class="postInfo-container-item" prop="conditions">
              <el-select v-model="temp.conditionIds" multiple placeholder="请选择（可多选）" @change="getConditionOptions" track-by="value" label="label">
                <el-option
                  v-for="item in conditions"
                  :key="item.id"
                  :label="item.condition"
                  :value="item.id">
                </el-option>
              </el-select>
          </el-form-item> 

          
          <el-row>
            <el-col :span="14">
              <el-form-item label="设置关联课程" prop='courseIds'>
                <el-button size="mini" type="primary" @click="chooseCommodity(commodityData)">选择课程</el-button>
                <ul >
                  <li style="marginRight: 0px" v-for="(item, index) of this.commodityName" :key="index">{{ item }}</li>
                </ul>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="14">
              <el-form-item label="设置关联院校" prop='academyIds'>
                <el-button size="mini" type="primary" @click="chooseSchool(academyData)">选择院校</el-button>
                <ul >
                  <li style="marginRight: 0px" v-for="(item, index) of this.academyName" :key="index">{{ item }}</li>
                </ul>
              </el-form-item>
            </el-col>
          </el-row>          

        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="success" @click="handleviewShowClick">预览</el-button>
        <el-button type="primary" @click="updateData()" :loading="updateButtonStatus">确定</el-button>
      </div>

    </el-dialog>

    <div class="viewShow">
      <el-dialog :show-close="false" :visible.sync="viewShowDialog" >
        <div class="information-cont">
          <h3>{{ temp.pathName }}</h3>
          <div class="smallLine">
            <span class="time">{{ temp.modifyTime|dateformat('YYYY-MM-DD HH:mm') }}</span>
          </div>
          <div class="artical-cont" v-html="temp.pathDefine"></div>
        </div>    
      </el-dialog>
    </div>

    <set-commodities :dialog="setComDialog" :setMsgObj="{setCommodityLists}" @cancel="setComDialogCancel" @handleDialogSaveCom="handleDialogSaveCom"></set-commodities>
    <set-academy :dialog="setDialog" :setMsgObj="{setSchoolLists}" @cancel="setDialogCancel" @handleDialogSaveArr="handleDialogSaveArr"></set-academy>


  </div>
</template>

<script>
import setCommodities from './components/setCommodities'
import setAcademy from './components/setAcademy'
import { getDel, getInfo, getMod, getList, getDelCon, getDelAca, getDelCou, getCondits } from '@/api/path'
import { getToken } from '@/utils/auth' // 验权
import Tinymce from '@/components/Tinymce'
import Multiselect from 'vue-multiselect' // 使用的一个多选框组件，element-ui的select不能满足所有需求
import 'vue-multiselect/dist/vue-multiselect.min.css' // 多选框组件css
import { getAreaList } from '@/api/activity'
export default {
  // inject: ['reload'],
  name: 'list',
  components: { Tinymce, Multiselect, setCommodities, setAcademy },
  data() {
    return {
      preventSumit:false,
      progressFactor:0.96,
      uploadProgress:0,
      headers: {},
      fileList:[],
      fileList_icon:[],
      inputVisible: false,
      inputValue: '',
      brandListOptions: [],
      dateformat: '',
      conditions:[],
      lessonData: [], //课程列表
      typeDialogVisible: false,
      isCreateCommodity: true,
      lessonType: 1,
      condition: [],
      commodityData: [],
      commodityName: [],
      academyData: [],
      academyName: [],
      showDialog: false,
      setDialog: false,
      setComDialog: false,
      setSchoolLists: [],
      setCommodityLists: [],
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      temp: {
        pathName:null,
        icon:null,
        pathDefine:null,
        suitCrowd: '',
        testSchedule: '',
        process: '',
        testForm: '',
        commonSense: '',
        sort: 0,
        videoIntroduce:null,
        conditionIds:[],
        courseIds:[],
        academyIds:[]
      },
      dialogFormVisible: false,
      rules: {
        pathName: [{ required: true, message: '名称必填', trigger: 'blur' }],
        icon: [{ type: 'date', required: true, message: '图标必传', trigger: 'change' }],
        pathDefine: [{ required: true, message: '定义必填', trigger: 'blur' }],
        suitCrowd: [{ required: true, message: '适合人群必填', trigger: 'blur' }],
        testSchedule: [{ required: true, message: '报考时间必填', trigger: 'blur' }],
        process: [{ required: true, message: '报考流程必填', trigger: 'blur' }],
        testForm: [{ required: true, message: '考试形式必填', trigger: 'blur' }],
        commonSense: [{ required: true, message: '报考常识必填', trigger: 'blur' }]
      },
      updateButtonStatus : false,
      viewShowDialog: false,
      notesParams: {
        topicId: null,
        pageNo: 1,
        pageSize: 10
      },
      dialogNotesVisible: false

    }
  },
  mounted() {
    this.getList()
    this.getConditionOptions()
    this.headers = { accessToken: getToken() }
  },
  methods: {

    //上传视频
    onBeforeUpload(file){
      this.progressFactor = Math.random(1)
      this.preventSumit = true
    },
    uploadSuccess(response, file, fileList) {
      const { code, data:{ picUrlList }, message } = response
      if(code == 0){
        this.fileList = [{ name:picUrlList[0], url:picUrlList[0] }]
        this.uploadProgress = 100
        this.preventSumit = false
        this.temp.videoIntroduce = this.fileList[0].url
        setTimeout(() => { this.uploadProgress = 0 }, 1000)
      }else{
        this.$refs.upload.clearFiles()
        this.$notify({
          title: '失败',
          message: message,
          type: 'error',
          duration: 3000
        })
        this.preventSumit = false
      }
    },
    handleRemoveVideo(file) {
      this.$refs.upload.clearFiles()
      this.fileList = []
      this.temp.videoIntroduce = ''
    },
    handProgress(file) {
      this.uploadProgress = parseInt(file.percent * this.progressFactor)
    },
    clearUpload() {
      if (!this.fileList.length) return false
      this.$refs.upload.clearFiles()
      this.fileList = []
      this.temp.videoIntroduce = ''
    },

    //筛选条件
    getConditionOptions(){
      getCondits().then(response => {
        const { code, data } = response
        if (code == 0) {
          this.conditions = data
        }
      })
    },
    //选择课程
    chooseCommodity(commodityData) {
      this.setCommodityLists = commodityData
      this.setComDialog = true
    },
    //选择院校
    chooseSchool(academyData) {
      this.setSchoolLists = academyData
      this.setDialog = true
    },
    handleDialogSaveArr(data) {
      const arr = []
      const name = []
      for (const item of data) {
        arr.push(item.academyId)
        name.push(item.academyName)
      }
      this.temp.academyIds = arr
      this.academyName = name
      this.academyData = data
      this.setDialog = false
    },
    handleDialogSaveCom(data) {
      const arr = []
      const name = []
      for (const item of data) {
        arr.push(item.courseId)
        name.push(item.title)
      }
      this.temp.courseIds = arr
      this.commodityName = name
      this.commodityData = data
      this.setComDialog = false
    },
    setDialogCancel() {
      this.setDialog = false
    },
    setComDialogCancel() {
      this.setComDialog = false
    },
    //删除单个条件
    deleteCondition(conditions, pathId){
      const _that = this
      this.$confirm(`是否将 “${conditions.condition}” 从该路径的权限中删除？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        const params = {
          conditionId: conditions.id,
          pathId
        }
        getDelCon(params).then(response => {
          if (response.code == 0) {
            this.$message({
              message: '删除成功',
              type: 'success',
              center: true
            })
            _that.getList()
          }
        })
      }).catch(() => {})
    },
    //删除单个课程
    deleteCourse(course, pathId){
      const _that = this
      this.$confirm(`是否将 “${course.title}” 从该路径的权限中删除？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        const params = {
          courseId: course.courseId,
          pathId
        }
        getDelCou(params).then(response => {
          if (response.code == 0) {
            this.$message({
              message: '删除成功',
              type: 'success',
              center: true
            })
            _that.getList()
          }
        })
      }).catch(() => {})
    },
    //删除单个院校
    deleteAcademy(academy, pathId){
      const _that = this
      this.$confirm(`是否将 “${academy.academyName}” 从该路径的权限中删除？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        const params = {
          academyId: academy.academyId,
          pathId
        }
        getDelAca(params).then(response => {
          if (response.code == 0) {
            this.$message({
              message: '删除成功',
              type: 'success',
              center: true
            })
            _that.getList()
          }
        })
      }).catch(() => {})
    },

    handleSizeNotesChange(val) {
      this.notesParams.pageSize = val
      this.getList()
    },
    handleCurrentNotesChange(val) {
      this.notesParams.pageNo = val
      this.getList()
    },

    // 查看预览
    handleviewShowClick() {
      this.viewShowDialog = true
    },
    handleClose() {
      this.$confirm('数据未保存，确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogFormVisible = false
      }).catch(() => {})
    },
    getSortList(filed){
      const { prop, order } = filed
      const { listQuery } = this
      listQuery['sortField'] = prop
      if(prop){
        listQuery['sortWay'] = order == 'descending' ? 'DESC' : 'ASC'
      }else{
        listQuery['sortWay'] = null
      }
      this.listQuery = listQuery
      this.getList()
    },
    handleUploadSuccess(rst, file, fileList) {
      const { code, data: { picUrlList } } = rst
      const { temp } = this
      if (code == 0) {
        temp['icon'] = picUrlList[0]
        this.temp.file = [{ name:file.url, url:file.url }]
      }
    },
    handlePreview(file) {
    },
    handleRemove(file, fileList) {
      this.temp['icon'] = ''
      this.temp['file'] = []
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.temp.labels.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getList() {
      this.listLoading = true
      const params = this.listQuery

      getList(params).then(response => {
        const { code, data: { total, list } } = response
        if (code == 0) {
          this.total = total
          this.list = list
          this.listLoading = false
        }
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    //查看详情
    handleModifyStatus(row) {
      getInfo(row.id).then(response => {
        const { code, data } = response
        data.updateTime = new Date(data.updateTime)
        data.file = [{ name: data.icon, url: data.icon }]
        this.temp = data
        const conditionIds = []
        const conditionNames = []
        const courseIds = []
        const courseNames = []
        const academyIds = []
        const academyNames = []
        this.commodityData = data.courseInfo
        this.academyData = data.academyInfo
        for(const item of data.conditionInfo){
          conditionIds.push(item.id)
          conditionNames.push(item.condition)
        }
        this.condition = conditionNames
        this.temp.conditionIds = conditionIds
        for(const item of data.courseInfo){
          courseIds.push(item.courseId)
          courseNames.push(item.title)
        }
        this.commodityName = courseNames
        this.temp.courseIds = courseIds
        for(const item of data.academyInfo){
          academyIds.push(item.academyId)
          academyNames.push(item.academyName)
        }
        this.academyName = academyNames
        this.temp.academyIds = academyIds
        this.dialogFormVisible = true
      })
    },
    //编辑
    updateData() {
      this.updateButtonStatus = true
      // console.log("temp",this.temp);

      getMod(this.temp).then(response => {
        const { code, message } = response
        if (code == 0) {
          this.getList()
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        }else{
          this.$message({
            title: '失败',
            message: message,
            type: 'error',
            duration: 2000
          })
        }
      }).catch(err => {})
        .finally(() => {
          this.updateButtonStatus = false
          // this.reload()
        })
    },
    //删除
    handleDelete(idx, row) {
      const { id } = row
      this.$confirm('确定要进行删除操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        getDel(id).then(response => {
          const { code } = response
          if (code == 0) {
            this.$notify({
              title: '成功',
              message: '删除路径成功',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(idx)
            this.list.splice(idx, 1)
            this.total--
          } else {
            this.$notify({
              title: '失败',
              message: '删除路径失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {
      })
    },
    handleRefresh() {
      this.list = null
      this.total = null
      this.listQuery.pageNo = 1
      this.getList()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>

.viewShow {

  /deep/ .el-dialog {
    width: 350px;
    height: 760px;
    padding: 100px 12px;
    border-radius: 50px;
    background: url('../../assets/phone.png') no-repeat;
    background-size: 100% 100%; 

    .el-dialog__header {
      padding: 0;
    }

    .el-dialog__body {
      padding: 0;
      background: #fff;
      width: 100%;
      height: 100%;

      .information-cont{
        padding: 0 15px;
        background: #fff;
        white-space:normal; 
        word-break:break-all;
        height: 100%;
        overflow-y: auto;

        h3 {
          font-size: 20px;
          line-height: 32px;
          color: #333333;
          font-weight: bold;
          padding-top: 15px;
          margin: 0;

        }

        .smallLine{
          display: flex;
          display: -webkit-flex;
          justify-content:space-between;
          -webkit-justify-content: space-between;
          align-items: center;
          -webkit-align-items: center;
          font-size: 13px;
          color: #BBB;
          padding-top: 20px;
          padding-bottom: 17px;
          border-bottom: 1px solid #E5E8ED;
          .watch {
            padding: 0 0 0 20px;
            font-size: 17px;
            color: #C7C7C7;
          }
        }

        .artical-cont{
          padding-top: 16px;
          font-size: 15px;
          overflow: hidden;
          img{
            width: 100%;
          }
        }

      }

    }

  }

}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container {
  padding: 20px;
}
.pagination-container {
  margin-top: 30px;
}
.widht{
  width: 180px;
}
.timeWidht{
  width: 300px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
